package com.itzmn.newcode.offer1;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/19 13:46
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description: 链表中倒数第k个元素
 *
 *  输入一个链表，输出该链表中倒数第k个结点。
 *
 *  思路：遍历链表得到尾部，然后反向遍历
 *
 */
public class _14_TheKthElementFromTheBottomOfTheList {


    public static void main(String[] args) {

        new _14_TheKthElementFromTheBottomOfTheList().test();
    }

    private void test() {

        ListNode listNode = initListNode();
        FindKthToTail(listNode,2);

    }

    public ListNode FindKthToTail(ListNode head,int k) {

        int count = 0;
        ListNode temp = head;

        while (head != null){
            head = head.next;
            count++;
        }
        if (k>count || k <= 0){
            return null;
        }

        int j =0;
        while (j!=count-k){
            temp = temp.next;
            j++;
        }
        System.out.println(temp.val);

        return temp;


    }

    /**
     * 初始化链表
     * @return
     */
    public ListNode initListNode(){

        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        return listNode1;
    }

    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
